import cache from '@/utils/cache';
import axios from 'axios';

class Request {
  instance;

  constructor(config) {
    this.instance = axios.create(config);
    // 注册全局请求拦截器
    this.instance.interceptors.request.use(
      (config) => {
        const token = cache.getCache('token');
        if (token) {
          config.headers['Authorization'] = cache.getCache('token');
        }
        return config;
      },
      (err) => {
        return Promise.reject(err);
      }
    );
    // 注册全局响应拦截器
    this.instance.interceptors.response.use(
      (res) => {
        return res.data;
      },
      (err) => {
        return Promise.reject(err);
      }
    );
  }

  get(url, config) {
    return this.instance.request({
      url,
      method: 'get',
      ...config
    });
  }

  post(url, config) {
    return this.instance.request({
      url,
      method: 'post',
      ...config
    });
  }

  request(config) {
    return this.instance.request(config);
  }
}

export default Request;
